<template>
  <div class="my-favorites">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon>
            <StarFilled />
          </el-icon>
          我的收藏
        </h1>
        <p class="page-description">管理您收藏的模板</p>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters-section">
      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="搜索收藏的模板..." clearable @input="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>

      <div class="filter-controls">
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="loadFavorites">
          <el-option label="全部分类" value="" />
          <el-option v-for="category in templateCategories" :key="category.code" :label="category.name"
            :value="category.code" />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式" @change="loadFavorites">
          <el-option label="收藏时间（最新）" value="created_desc" />
          <el-option label="收藏时间（最早）" value="created_asc" />
          <el-option label="模板评分（高到低）" value="rating_desc" />
          <el-option label="模板评分（低到高）" value="rating_asc" />
          <el-option label="使用次数（多到少）" value="usage_desc" />
        </el-select>
      </div>
    </div>

    <!-- 收藏统计 -->
    <div class="stats-section">
      <el-card class="stats-card">
        <div class="stats-content">
          <div class="stat-item">
            <span class="stat-number">{{ totalCount }}</span>
            <span class="stat-label">收藏模板</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ categoriesCount }}</span>
            <span class="stat-label">涉及分类</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 收藏列表 -->
    <div class="favorites-section">
      <div v-loading="loading" class="favorites-grid">
        <template-card v-for="template in filteredFavorites" :key="template.id" :template="template"
          :show-featured-badge="false" @use="handleUseTemplate" @favorite="handleUnfavorite" @rate="handleRateTemplate"
          @preview="handlePreviewTemplate" />
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && favorites.length === 0" class="empty-state">
        <el-empty description="您还没有收藏任何模板">
          <el-button type="primary" @click="goToMarket">
            去模板广场看看
          </el-button>
        </el-empty>
      </div>

      <!-- 搜索无结果 -->
      <div v-if="!loading && favorites.length > 0 && filteredFavorites.length === 0" class="empty-state">
        <el-empty description="没有找到匹配的模板">
          <el-button @click="clearSearch">
            清除搜索条件
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalCount > pageSize" class="pagination-section">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[12, 24, 48]"
        :total="totalCount" layout="total, sizes, prev, pager, next, jumper" @size-change="loadFavorites"
        @current-change="loadFavorites" />
    </div>

    <!-- 模板预览对话框 -->
    <el-dialog v-model="showPreviewDialog" title="模板预览" width="800px">
      <div v-if="previewingTemplate" class="template-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">
            {{ previewingTemplate.name }}
          </el-descriptions-item>
          <el-descriptions-item label="创建者">
            {{ previewingTemplate.createdBy }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(previewingTemplate.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="使用次数">
            {{ previewingTemplate.downloadCount || 0 }} 次
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ previewingTemplate.description }}
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin: 20px 0 12px 0;">包含的软件</h4>
        <el-table :data="previewingTemplate.softwareList" style="width: 100%">
          <el-table-column label="软件名称">
            <template #default="scope">
              {{ scope.row.displayName || scope.row.name || '未知软件' }}
            </template>
          </el-table-column>
          <el-table-column label="版本" width="120">
            <template #default="scope">
              {{ scope.row.version || 'latest' }}
            </template>
          </el-table-column>
          <el-table-column label="分类" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getCategoryType(scope.row.category)">
                {{ scope.row.category || '其他' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPreviewDialog = false">关闭</el-button>
          <el-button type="primary" @click="handleUseTemplate(previewingTemplate)">
            使用此模板
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import TemplateCard from '@/components/TemplateCard.vue'
import { TEMPLATE_CATEGORIES, getCategoryType } from '@/constants/templateCategories'
import { useSoftwareStore } from '@/stores/software'
import { useTemplateStore } from '@/stores/template'
import { useUserStore } from '@/stores/user'
import { Search, StarFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const templateStore = useTemplateStore()
const softwareStore = useSoftwareStore()

// 模板分类配置
const templateCategories = TEMPLATE_CATEGORIES

// 响应式数据
const loading = ref(false)
const favorites = ref([])
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('created_desc')
const currentPage = ref(1)
const pageSize = ref(12)
const totalCount = ref(0)

// 预览相关
const showPreviewDialog = ref(false)
const previewingTemplate = ref(null)

// 计算属性
const filteredFavorites = computed(() =>
{
  let result = [...favorites.value]

  // 搜索过滤
  if (searchQuery.value)
  {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(template =>
      template.name.toLowerCase().includes(query) ||
      template.description?.toLowerCase().includes(query) ||
      template.tags?.some(tag => tag.toLowerCase().includes(query))
    )
  }

  // 分类过滤
  if (selectedCategory.value)
  {
    result = result.filter(template => template.category === selectedCategory.value)
  }

  return result
})

const categoriesCount = computed(() =>
{
  const categories = new Set(favorites.value.map(t => t.category))
  return categories.size
})

// 方法
const loadFavorites = async () =>
{
  try
  {
    loading.value = true

    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    // 开源版本跳过收藏API调用
    const isOpenSourceVersion = true // 开源版本标识
    if (isOpenSourceVersion)
    {
      console.log('📊 开源版本跳过收藏API调用')
      favorites.value = []
      totalCount.value = 0
      ElMessage.info('开源版本暂不支持收藏功能')
      return
    }

    const response = await fetch('/api/template-enhancements/favorites/details', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()
    if (result.code === 200)
    {
      favorites.value = result.data || []
      totalCount.value = favorites.value.length

      // 同步收藏模板状态到store
      templateStore.batchSetTemplateStates(favorites.value)
      templateStore.batchSyncTemplateStates(favorites.value)
    } else
    {
      throw new Error(result.message || '获取收藏列表失败')
    }
  } catch (error)
  {
    console.error('加载收藏失败:', error)
    ElMessage.error('加载收藏失败: ' + error.message)
  } finally
  {
    loading.value = false
  }
}

const handleSearch = () =>
{
  // 搜索是实时的，通过计算属性处理
}

const handleUseTemplate = async (template) =>
{
  try
  {
    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    const confirmed = await ElMessageBox.confirm(
      `确定要使用模板"${template.name}"吗？这将导入模板中的软件配置。`,
      '使用模板',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    if (confirmed)
    {
      // 调用后端API记录使用次数
      const useResponse = await fetch(`/api/templates/${template.id}/use`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${userStore.token}`
        }
      })

      const useResult = await useResponse.json()

      if (useResult.code === 200)
      {
        // 清空当前选择
        softwareStore.clearSelectedSoftware()

        // 添加模板中的软件
        if (template.softwareList && template.softwareList.length > 0)
        {
          template.softwareList.forEach(software =>
          {
            softwareStore.addSoftware({
              id: software.id,
              name: software.name,
              displayName: software.displayName,
              latestVersion: { version: software.version }
            })
          })
        }

        // 更新本地模板的使用次数显示
        template.downloadCount = (template.downloadCount || 0) + 1

        ElMessage.success(`已应用模板：${template.name}`)
        router.push('/software')
      } else
      {
        throw new Error(useResult.message || '记录使用失败')
      }
    }
  } catch (error)
  {
    if (error !== 'cancel')
    {
      console.error('使用模板失败:', error)
      ElMessage.error('使用模板失败: ' + error.message)
    }
  }
}

const handleUnfavorite = async (template) =>
{
  try
  {
    const confirmed = await ElMessageBox.confirm(
      `确定要取消收藏模板"${template.name}"吗？`,
      '确认取消收藏',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (confirmed)
    {
      const response = await fetch(`/api/template-enhancements/${template.id}/favorite`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${userStore.token}`
        }
      })

      const result = await response.json()
      if (result.code === 200)
      {
        ElMessage.success('取消收藏成功')

        // 更新全局状态
        templateStore.setFavoriteState(template.id, false)

        // 从列表中移除
        favorites.value = favorites.value.filter(t => t.id !== template.id)
        totalCount.value = favorites.value.length
      } else
      {
        throw new Error(result.message || '取消收藏失败')
      }
    }
  } catch (error)
  {
    if (error !== 'cancel')
    {
      ElMessage.error('取消收藏失败: ' + error.message)
    }
  }
}

const handleRateTemplate = async (template, rating) =>
{
  try
  {
    if (!userStore.isLoggedIn)
    {
      ElMessage.warning('请先登录')
      return
    }

    const response = await fetch(`/api/template-enhancements/${template.id}/rating`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      },
      body: JSON.stringify({ rating })
    })

    const result = await response.json()
    if (result.code === 200)
    {
      ElMessage.success('评分成功')
      // 重新加载收藏列表以获取最新评分
      loadFavorites()
    } else
    {
      throw new Error(result.message || '评分失败')
    }
  } catch (error)
  {
    ElMessage.error('评分失败: ' + error.message)
  }
}

const goToMarket = () =>
{
  router.push('/templates')
}

const clearSearch = () =>
{
  searchQuery.value = ''
  selectedCategory.value = ''
}

const handlePreviewTemplate = (template) =>
{
  previewingTemplate.value = template
  showPreviewDialog.value = true
}

// 工具函数
const formatDate = (dateString) =>
{
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 生命周期
onMounted(() =>
{
  loadFavorites()
})

// 监听用户登录状态变化
watch(() => userStore.isLoggedIn, (newValue) =>
{
  if (newValue)
  {
    loadFavorites()
  } else
  {
    favorites.value = []
    totalCount.value = 0
  }
})
</script>

<style scoped>
.my-favorites {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.header-content {
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.filters-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
  flex-wrap: wrap;
}

.search-bar {
  flex: 1;
  min-width: 300px;
}

.filter-controls {
  display: flex;
  gap: 12px;
}

.stats-section {
  margin-bottom: 24px;
}

.stats-card {
  border-radius: 12px;
}

.stats-content {
  display: flex;
  gap: 32px;
  justify-content: center;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: 600;
  color: #3b82f6;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.empty-state {
  text-align: center;
  padding: 48px 24px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

@media (max-width: 768px) {
  .my-favorites {
    padding: 16px;
  }

  .filters-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-bar {
    min-width: auto;
  }

  .filter-controls {
    justify-content: space-between;
  }

  .stats-content {
    gap: 16px;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style>
